package org.fujene.diskblock;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javassist.NotFoundException;

import org.fujene.memoryblock.MemoryBlock;
import org.fujene.memoryblock.SkipPointerBlock;
import org.fujene.structure.LookupPointer;
import org.fujene.toolbox.ByteConverter;

public class SkipPointerDiskBlock extends DiskBlock{
	public SkipPointerDiskBlock(File fileDesc) throws NotFoundException{
		super(fileDesc);
	}

	public SkipPointerDiskBlock(SkipPointerBlock memBlock, String dir){
		super(memBlock, dir);
	}

	public int getSkipType() throws Exception{
		return getOption(SkipPointerBlock.OPT_TYPE);
	}

	public int getNextblock() throws Exception{
		return getOption(SkipPointerBlock.OPT_NBLOCK);
	}

	public int getLength() throws Exception{
		return getOption(SkipPointerBlock.OPT_LEN);
	}

	public LookupPointer getPointer(int index) throws Exception{
		// OutOfBounds
		if(index >= getOption(0)) return null;
		return LookupPointer.fromBytes(getBody(index * PTR, PTR));
	}

	@Override
	public int toMemory(MemoryBlock memBlock){
		if(memBlock instanceof SkipPointerBlock){
			try{
				for(int i = 0; i < SkipPointerBlock.OPTSIZE; i++)
					memBlock.setOption(i, this.getOption(i));
				memBlock.setBody(this.getBody(0, this.bodySize), 0);
				memBlock.setBodyVacancy(this.bodyVacancy);
			}catch(Exception e){}
		}
		return this.bodySize - this.bodyVacancy;
	}

	@Override
	public byte[] getData(){
		ByteArrayOutputStream stream = new ByteArrayOutputStream(this.bodySize + SkipPointerBlock.OPTSIZE * 4);

		try{
			stream.write(ByteConverter.intToByte(this.getOption(SkipPointerBlock.OPT_LEN), 4));
			stream.write(ByteConverter.intToByte(this.getOption(SkipPointerBlock.OPT_NBLOCK), 4));
			stream.write(ByteConverter.intToByte(this.getOption(SkipPointerBlock.OPT_TYPE), 4));
			stream.write(this.getBody(0, this.bodySize));
		}catch(IOException e){}

		return stream.toByteArray();
	}
}
